//
//  HMComposeViewController.swift
//  Weibo
//
//  Created by HM on 16/5/28.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class HMComposeViewController: UIViewController {

    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send() {
        print("发送")
        
        HMNetworkTools.sharedTools.sendStatus(textView.text, images: pictureSelector.images) { (responseObject, error) in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            
            //成功
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
        }
    }
    
    @objc private func selectPicture() {
        print("选中图片")
        pictureSelector.view.snp_updateConstraints { (make) in
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
    }
    
    @objc private func selectEmoticon() {
        print("选择表情")
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置View的背景颜色
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
        //注册通知
        registerNotification()
        //成为第一响应者 不建议在viewdidload中执行
        //textView.becomeFirstResponder()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if pictureSelector.images.count == 0 {
            //成为第一响应者
            textView.becomeFirstResponder()
        }
        
    }
    
    //注册通知
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HMComposeViewController.keyboardChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    //键盘将要改变frame  toolBar需要做动画效果
    @objc private func keyboardChange(n: NSNotification) {
        print(n)
        //获取键盘显示或者隐藏的动画时间
        let time_t = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //结构体能够直接存放在字典中?   --> 需要转换为 NSValue 才能存储
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        print(time_t,rect)
        //获取键盘的frame
        let offsetY = -ScreenHeight + rect.origin.y
        UIView.animateWithDuration(time_t) { 
            //修改toolbar 应该修改约束 不能够直接修改frame
            self.toolBar.snp_updateConstraints(closure: { (make) in
                make.bottom.equalTo(offsetY)
            })
            //提前刷新页面
            self.view.layoutIfNeeded()
        }
    }
    
    private lazy var rightBarbuttonItem: UIBarButtonItem = {
        let btn = UIButton()
        //设置文案
        btn.setTitle("发送", forState: .Normal)
        //添加点击事件
        btn.addTarget(self, action:#selector(HMComposeViewController.send) , forControlEvents: .TouchUpInside)
        //设置根据内容显示
        //设置文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        return barButtonItem
    }()
    
    //文本输入视图 & 文本输入框
    private lazy var textView: UITextView = {
        let tv = UITextView()
        //tv.text = "因何而生,因何而战"
        tv.backgroundColor = UIColor(white: 0.8, alpha: 1)
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        //设置滚动视图键盘消失的方式
        tv.keyboardDismissMode = .OnDrag
        tv.alwaysBounceVertical = true
        tv.delegate = self
        return tv
    }()
    
    private lazy var placeHolderLabel: UILabel = UILabel(title: "因何而生,因何而战", font: 18, textColor: UIColor.lightGrayColor())
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //添加控制器的属性
    private lazy var pictureSelector: HMPictureSelectorController = HMPictureSelectorController()
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}


//UI搭建
extension HMComposeViewController {
    
    
    private func setupUI() {
        setNavBar()
        setTextView()
        setToolBar()
        setSeletorVC()
    }
    
    private func setSeletorVC() {
        //添加子视图控制器
        self.addChildViewController(pictureSelector)
        //使用控制器的view
        self.view.addSubview(pictureSelector.view)
        
        //将toolbar移动到最前面
        self.view.bringSubviewToFront(toolBar)
        
        pictureSelector.view.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    //设置底部工具条
    private func setToolBar() {
        self.view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            //工具条有默认高度
        }
        
        var items = [UIBarButtonItem]()
        //操作数据 添加UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        for item in itemSettings {
            let imageName = item["imageName"]
            let action = item["actionName"]!
            //添加自定义UIBarButtonItem
            let item  = UIBarButtonItem(imageName: imageName, title: nil, target: self, action: Selector(action))
            items.append(item)
            
            //添加弹簧 FlexibleSpace 可伸缩瘫痪
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        //移除最后一个
        items.removeLast()
        toolBar.items = items
    }
    
    //设置文本输入视图
    private func setTextView() {
        self.view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            //设置高度
            make.height.equalTo(ScreenHeight / 3)
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
    }
    
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(HMComposeViewController.close))
        navigationItem.rightBarButtonItem = rightBarbuttonItem
        ///  设置右边按钮不可交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置导航条自定义视图  是nil 不能够直接添加视图
        print(navigationItem.titleView)
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        let titleLabel = UILabel(title: "发布微博", font: 16, textColor: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: HMUserAccountViewModel.sharedAccountViewModel.userAccount?.name ?? "", font: 13, textColor: UIColor.lightGrayColor())
        
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.top.equalTo(myView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.bottom.equalTo(myView.snp_bottom)
        }
        //赋值的操作
        navigationItem.titleView = myView
    }
}



extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //发生修改
        placeHolderLabel.hidden = textView.hasText()
        rightBarbuttonItem.enabled = textView.hasText()
    }
}
